#include "PadStackParser.h"

#include "LayerPadParser.h"
#include "LayerHoleParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

PadStackParser::PadStackParser(
    QStringParser *&_netParser
    , LayerHoleParser *&_layerHoleParser
    , LayerPadParser *&_layerPadParser
):    m_netParser(_netParser)
    , m_layerHoleParser(_layerHoleParser)
    , m_layerPadParser(_layerPadParser)
{

}

bool PadStackParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new PadStack());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("net")))
    {
        data = reader->attributes().value(QStringLiteral("net"));
        if (!m_netParser->parse(reader, data))
            return false;
        m_result->netOptional = Optional<QString>(m_netParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("LayerHole"))
        {
            if (!m_layerHoleParser->parse(reader))
                return false;
            auto result = m_layerHoleParser->result();
            m_result->layerHole = result;
        }
        else if (name == QStringLiteral("LayerPad"))
        {
            if (!m_layerPadParser->parse(reader))
                return false;
            auto result = m_layerPadParser->result();
            m_result->layerPadList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

PadStack *PadStackParser::result()
{
    return m_result.take();
}

}